package com.whiteape.book.ui.dialog;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flask.colorpicker.ColorPickerView;
import com.flask.colorpicker.builder.ColorPickerDialogBuilder;
import com.hwangjr.rxbus.RxBus;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.whiteape.book.R;
import com.whiteape.book.WaApp;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.page.PageLoader;
import com.whiteape.book.core.page.PageStyleNew;
import com.whiteape.book.ui.activity.BookReadActivity;
import com.whiteape.book.ui.adapter.ReadSettingColorAdapter;
import com.whiteape.book.utils.DisplayUtil;
import com.whiteape.book.utils.FileUtils;
import com.whiteape.book.utils.JumpPermissionManagement;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.ToastUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * 小说背景选择:颜色或者图片，选取图片前需要先判断权限
 */
public class NovelBackgroundDialogFragment extends DialogFragment implements View.OnClickListener, BaseQuickAdapter.OnItemLongClickListener, BaseQuickAdapter.OnItemClickListener {

    private ImageView ivBack;
    private TextView tvFgAdd;
    private TextView tvBgAdd;
    private TextView tvBgPicAdd;
    private TextView tvAddPageStyle;
    private Disposable disposable;
    private final int COLOR_TYPE_BG = 0;
    private final int COLOR_TYPE_FG = 1;
    private RecyclerView rvBg, rvBgPic, rvFg;
    private List<String> bgData, bgPicData, fgData;
    private ReadSettingColorAdapter bgAdapter, bgPicAdapter, fgAdapter;

    private PageLoader mPageLoader;
    private Activity mActivity;
    private String mCurrentBg, mCurrentFg;

    public NovelBackgroundDialogFragment(Activity activity, PageLoader pageLoader) {
        this.mActivity = activity;
        this.mPageLoader = pageLoader;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        WindowManager.LayoutParams params = getDialog().getWindow()
                .getAttributes();
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        params.windowAnimations = R.style.anim_slide_right_in_out;
        getDialog().getWindow().setAttributes(params);
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().setCanceledOnTouchOutside(true);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View root = inflater.inflate(R.layout.dialog_read_bg_setting, container, false);

        initView(root);
        initData();
        initAdapter();
        RxBus.get().register(this);
        setCancelable(false);

        return root;
    }

    private void initView(View root) {

        ivBack = root.findViewById(R.id.iv_back);
        tvBgAdd = root.findViewById(R.id.tv_read_bg_setting_add_bg);
        tvBgPicAdd = root.findViewById(R.id.tv_read_bg_setting_add_bg_pic);
        tvAddPageStyle = root.findViewById(R.id.tv_add_page_style);
        tvFgAdd = root.findViewById(R.id.tv_read_bg_setting_add_fg);
        rvBg = root.findViewById(R.id.rv_read_bg);
        rvBgPic = root.findViewById(R.id.rv_read_bg_pic);
        rvFg = root.findViewById(R.id.rv_read_fg);
        ivBack.setOnClickListener(this);
        tvBgAdd.setOnClickListener(this);
        tvBgPicAdd.setOnClickListener(this);
        tvFgAdd.setOnClickListener(this);
        tvAddPageStyle.setOnClickListener(this);

    }

    private void initColorsForFirstTime() {
        String bgColorStr = "#000000;#CEC29C;#CCEBCC;#AAAAAA;#D1CEC5;#001C27";
        String fgColorStr = "#99ffffff;#2C2C2C;#2F332D;#92918C;#383429;#627176";

        ReadSettingManager.getInstance().addReadColors(ReadSettingManager.READ_COLOR_TYPE_BG, bgColorStr);
        ReadSettingManager.getInstance().addReadColors(ReadSettingManager.READ_COLOR_TYPE_FG, fgColorStr);
    }

    private void initData() {
        if (!ReadSettingManager.getInstance().isReadColorsInited()) {
            initColorsForFirstTime();
            ReadSettingManager.getInstance().setReadColorsInited(true);
        }
        bgData = new ArrayList<>();
        bgPicData = new ArrayList<>();
        fgData = new ArrayList<>();
        bgData.addAll(ReadSettingManager.getInstance().getReadColors(ReadSettingManager.READ_COLOR_TYPE_BG));
        bgPicData.addAll(ReadSettingManager.getInstance().getReadColors(ReadSettingManager.READ_COLOR_TYPE_BG_PIC));
        fgData.addAll(ReadSettingManager.getInstance().getReadColors(ReadSettingManager.READ_COLOR_TYPE_FG));
    }

    private void initAdapter() {

        PageStyleNew currentPageStyle = ReadSettingManager.getInstance().getPageStyleNew();
        mCurrentBg = currentPageStyle.getBgColor();
        mCurrentFg = currentPageStyle.getFontColor();

        bgAdapter = new ReadSettingColorAdapter(R.layout.item_read_setting_color, bgData);
        bgPicAdapter = new ReadSettingColorAdapter(R.layout.item_read_setting_color, bgPicData);
        fgAdapter = new ReadSettingColorAdapter(R.layout.item_read_setting_color, fgData);
        bgAdapter.setSelected(mCurrentBg);
        bgPicAdapter.setSelected(mCurrentBg);
        fgAdapter.setSelected(mCurrentFg);

        rvBg.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayout.HORIZONTAL, false));
        rvBgPic.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayout.HORIZONTAL, false));
        rvFg.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayout.HORIZONTAL, false));

        rvBg.setAdapter(bgAdapter);
        rvBgPic.setAdapter(bgPicAdapter);
        rvFg.setAdapter(fgAdapter);


        bgAdapter.setOnItemClickListener(this);
        bgPicAdapter.setOnItemClickListener(this);
        fgAdapter.setOnItemClickListener(this);
        bgAdapter.setOnItemLongClickListener(this);
        bgPicAdapter.setOnItemLongClickListener(this);
        fgAdapter.setOnItemLongClickListener(this);


    }
//    private void selectPicker() {
//        String choices[] = new String[]{"使用颜色作为背景", "使用图片作为背景"};
//        new AlertDialog.Builder(getActivity())
//                .setTitle("请选择")
//                .setItems(choices, ((dialog, which) -> {
//                    switch (which) {
//                        case 0:
//                            showColorPicker();
//                            break;
//                        case 1:
////                            showPicturePicker();
//                            checkPermissionAndShowPicturePicker();
//                            break;
//                    }
//
//                }))
//                .show();
//    }

    private void rxPermissionRequest(RxPermissions rxPermissions) {
        String permissionRequired = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        disposable = rxPermissions.requestEach(permissionRequired)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // `permission.name` is granted !
                        showPicturePicker();

                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                        if (mActivity == null) {
                            ToastUtils.show("必须授权才能下一步操作哦");
                            return;
                        }
//                        importSiteSourceBy(type);
                        new androidx.appcompat.app.AlertDialog.Builder(mActivity)
                                .setTitle(R.string.wa_common_tip)
                                .setMessage(R.string.permission_request_sdcard)
                                .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                                    dialogInterface.dismiss();
                                    rxPermissionRequest(rxPermissions);
                                }))
                                .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                                    dialogInterface.dismiss();
                                    ToastUtils.show("已经拒绝权限，需要重新打开授权才可以导入本地图片哦");
                                })).show();
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                        if (mActivity == null) {
                            ToastUtils.show("已经拒绝权限，需要去系统设置打开权限哦");
                            return;
                        }
                        new androidx.appcompat.app.AlertDialog.Builder(mActivity)
                                .setTitle(R.string.wa_common_tip)
                                .setMessage(R.string.permission_request_sdcard_goto_setting)
                                .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                                    //goto setting
                                    dialogInterface.dismiss();
                                    JumpPermissionManagement.goToSetting(getActivity());

                                }))
                                .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                                    dialogInterface.dismiss();
                                    ToastUtils.show("已拒绝权限，无法导入图片");
                                })).show();

                    }
                });

    }


    private void checkPermissionAndShowPicturePicker() {

        RxPermissions rxPermissions = new RxPermissions(this);
        if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            showPicturePicker();
            return;
        }
        if (mActivity == null) {
            return;
        }
        new androidx.appcompat.app.AlertDialog.Builder(mActivity)
                .setTitle(R.string.wa_common_tip)
                .setMessage(R.string.permission_request_sdcard)
                .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                    dialogInterface.dismiss();

                    rxPermissionRequest(rxPermissions);
                }))
                .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                    dialogInterface.dismiss();
                    ToastUtils.show("已经拒绝权限，需要重新打开授权才可以导入本地网源哦");
                })).show();
    }

    private void showPicturePicker() {
        Matisse.from(getActivity())
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(1)
//                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(true) // Default is `true`
                .forResult(BookReadActivity.REQUEST_CODE_CHOOSE_PICTURE);

    }

    public void onPictureSelected(Uri uri) {
        //背景图选好了
        LogUtils.e("TWTW", "OOOOKK, uri is " + uri);
        String filePath = FileUtils.getRealPath(mActivity, uri);
        try {

            File file = new File(filePath);
            String fileName = file.getName();
            String newFilePath = FileUtils.getSavePath() + File.separator + "/bg/" +File.separator + fileName;
            boolean ret = FileUtils.copyFile(new FileInputStream(file), new File(newFilePath));
            if(!ret){
                ToastUtils.show("文件异常,");
                return;
            }
            bgPicData.add(newFilePath);
            mCurrentBg = newFilePath;
            ReadSettingManager.getInstance().setReadColors(ReadSettingManager.READ_COLOR_TYPE_BG_PIC, bgPicData);
            bgPicAdapter.setSelected(newFilePath);
            bgAdapter.setSelected("");
            refresh();
        } catch (Exception e) {
            ToastUtils.show("文件异常,"+e.getLocalizedMessage());
        }

    }

    private String getSavePath() {
        String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
        return sdcard + File.separator + "白猿搜书";
    }

    private void refresh() {
        bgPicAdapter.notifyDataSetChanged();
        bgAdapter.notifyDataSetChanged();
        fgAdapter.notifyDataSetChanged();
        if (mPageLoader != null) {
            mPageLoader.setPageStyle(new PageStyleNew(mCurrentBg, mCurrentFg));
        }
    }

    private void showColorPicker(int type) {
        Context context = mActivity;
        if (null == context) {
            context = WaApp.getInstance().getApplicationContext();
        }
        ColorPickerDialogBuilder builder = ColorPickerDialogBuilder
                .with(context)
                .setTitle("选择背景色")
                .showColorEdit(true)
                .setColorEditTextColor(Color.parseColor("#000000"))
                .showColorPreview(true)
                .initialColor(Color.parseColor("#ff3333"))
                .wheelType(ColorPickerView.WHEEL_TYPE.FLOWER)
                .density(12)
                .setPositiveButton("确定", ((dialogInterface, i, integers) -> {
                    if (type == COLOR_TYPE_BG) {
                        String bgColor = StringUtils.getColorHexString(integers[0]);
                        bgData.add(bgColor);
                        bgAdapter.setSelected(bgColor);
                        mCurrentBg = bgColor;
                        fgAdapter.setSelected("");
                        ReadSettingManager.getInstance().setReadColors(ReadSettingManager.READ_COLOR_TYPE_BG, bgData);
                    } else {
                        String fgColor = StringUtils.getColorHexString(integers[0]);
                        fgData.add(fgColor);
                        mCurrentFg = fgColor;
                        fgAdapter.setSelected(fgColor);
                        bgAdapter.setSelected("");
                        ReadSettingManager.getInstance().setReadColors(ReadSettingManager.READ_COLOR_TYPE_FG, fgData);
                    }
                    refresh();

                }))
                .setNegativeButton("取消", (dialog, which) -> {

                });
        builder.build().show();
    }

    @Override
    public void onClick(View v) {
        if (v == ivBack) {
//            makeSureToAdd(true);
            addColorMethod();
            dismiss();

        } else if (v == tvBgAdd) {
            showColorPicker(COLOR_TYPE_BG);

        } else if (v == tvFgAdd) {
            showColorPicker(COLOR_TYPE_FG);

        } else if (v == tvBgPicAdd) {
            checkPermissionAndShowPicturePicker();
        } else if (v == tvAddPageStyle) {
            makeSureToAdd(false);
        }
    }

    private void addColorMethod() {

        PageStyleNew pageStyleNew = new PageStyleNew(mCurrentBg, mCurrentFg);
        List<PageStyleNew> currentPageStyleList = ReadSettingManager.getInstance().getPageStyleAll();
        if (!currentPageStyleList.contains(pageStyleNew)) {
            currentPageStyleList.add(pageStyleNew);
        }
        ReadSettingManager.getInstance().setPageStyleNew(pageStyleNew);
        ReadSettingManager.getInstance().setPageStyleAll(currentPageStyleList);

        RxBus.get().post(RxEvent.READ_PAGE_STYLE_CHANGED, pageStyleNew);
    }

    private void makeSureToAdd(boolean exitDialog) {

        new AlertDialog.Builder(mActivity).setTitle("提示")
                .setMessage("确认新增该方案吗？")
                .setNegativeButton("取消", (dialog, which) -> {
                    if (exitDialog) {
                        NovelBackgroundDialogFragment.this.dismiss();
                    }
                })
                .setPositiveButton("确认", ((dialog, which) -> {
                    addColorMethod();
                    NovelBackgroundDialogFragment.this.dismiss();

                }))
                .show();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter == bgAdapter) {
            bgAdapter.setSelected(bgData.get(position));
            bgPicAdapter.setSelected("");
            mCurrentBg = bgData.get(position);
        } else if (adapter == bgPicAdapter) {
            bgPicAdapter.setSelected(bgPicData.get(position));
            bgAdapter.setSelected("");
            mCurrentBg = bgPicData.get(position);

        } else if (adapter == fgAdapter) {
            fgAdapter.setSelected(fgData.get(position));
            mCurrentFg = fgData.get(position);
        }
        refresh();
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        if ((adapter == bgAdapter && bgData.get(position).equals(bgAdapter.getSelected())) ||
                (adapter == bgPicAdapter && bgPicData.get(position).equals(bgPicAdapter.getSelected())) ||
                (adapter == fgAdapter && fgData.get(position).equals(fgAdapter.getSelected()))
        ) {
            ToastUtils.show("不能删除正在使用的配色");
            return true;

        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
                .setTitle("请注意")
                .setMessage("是否删除此项?")
                .setPositiveButton("确认", (dialog, which) -> {
                    adapter.remove(position);
                    adapter.notifyDataSetChanged();

                })
                .setNegativeButton("取消", (dialog, which) -> {

                });
        builder.show();
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getDialog() == null || getDialog().getWindow() == null || mActivity == null) {
            return;
        }
        getDialog().getWindow().setLayout(DisplayUtil.getScreenWidth(mActivity), DisplayUtil.dip2px(mActivity, 360));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        RxBus.get().unregister(this);
    }
}
